package com.example.waimai_demo.filter;

import com.alibaba.fastjson.JSON;
import com.example.waimai_demo.common.R;
import groovyjarjarantlr.CharScanner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    private static final AntPathMatcher antPathMatcher=new AntPathMatcher() ;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        //强转一下,向下转型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取url
        String uri = request.getRequestURI();
        String[] urls=new String[]{
          "/employee/login" ,
          "/employee/logout" ,
          "/backend/**",
          "/front/**"
        };
        boolean flag=checkURI(uri,urls);
        if(flag){
//            放行
            filterChain.doFilter(request,response);
            return;
        }
//        要判断请求从哪里出发
        String Agent=request.getHeader("Agent");
        if ("backend".equals(Agent)){
            if (request.getSession().getAttribute("employee")!=null){
                    filterChain.doFilter(request,response);
                    return;
            }

        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    private boolean checkURI(String uri, String[] urls) {
            for (String u:urls){
//                如果用户访问的地址中在url数组中/路径匹配 就返回true
                boolean match=antPathMatcher.match(u,uri);
                if (match){
                return true;
            }
        }
        //否则就是没有匹配到，不予放行
        return false;
    }

}



